<template>
  <el-dialog title="批量导入照片" v-model="visible" width="601px" top="10%">
    <el-upload class="upload-demo" drag action :auto-upload="false" :on-change="handleChange" :on-remove="handleRemove"
      :before-upload="beforeUpload" :limit="limitUpload" accept=".zip">
      <el-icon class="el-icon--upload"><upload-filled /></el-icon>
      <div class="el-upload__text">
        Drop file here or <em>click to upload</em>
      </div>
      <template #tip>
        <div class="el-upload__tip">
          <p>注：导入格式为ZIP文件包，包内图片命名规则为：</p>
          <p>用户：姓名-身份证（此处“-”为必须）</p>
          <p>例如：张三-123456</p>
        </div>
      </template>
    </el-upload>

    <template v-slot:footer>
      <el-button @click="visible = false">{{ $t("cancel") }}</el-button>
      <el-button type="primary" :loading="submitLoading" @click="dataFormSubmitHandle()">{{ $t("confirm") }}</el-button>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { reactive, ref } from "vue";
import baseService from "@/service/baseService";
import { IObject } from "@/types/interface";
import { useI18n } from "vue-i18n";
import { ElMessage, UploadProps, UploadUserFile } from "element-plus";
import { PersonnelType } from "@/constants/enum";
import app from "@/constants/app";
import { getCache, getToken } from "@/utils/cache";
import axios from "axios";
import { CacheTenantCode } from "@/constants/cacheKey";

const limitUpload = 1;
const { t } = useI18n();
const emit = defineEmits(["refreshDataList"]);

const visible = ref(false);
const dataFormRef = ref();
const submitLoading = ref(false);

const dataForm = reactive({
  file: "",
});

const rules = ref({
  name: [{ required: true, message: t("validate.required"), trigger: "blur" }],
  gender: [{ required: true, message: t("validate.required"), trigger: "change" }],
  status: [{ required: true, message: t("validate.required"), trigger: "change" }]
});

const init = () => {
  visible.value = true;
  // 重置表单数据
  if (dataFormRef.value) {
    dataFormRef.value.resetFields();
  }
};

const beforeUpload: UploadProps['beforeUpload'] = (rawFile) => {
  var testmsg = rawFile.name.substring(rawFile.name.lastIndexOf('.') + 1)
  const extension2 = testmsg === 'zip'
  const isLt100M = rawFile.size / 1024 / 1024 < 100

  if (!extension2) {
    ElMessage.error({
      message: '上传的文件只能是 ZIP格式!',
    });
    return;
  }
  if (!isLt100M) {
    ElMessage.error({
      message: '上传的文件限制100M!',
    });
    return;
  }
};

const file = ref<File>();
const handleChange: UploadProps['onChange'] = (rawFile) => {
  console.log('rawFile', rawFile);
  if (rawFile) {
    file.value = rawFile.raw;
  }
};

const handleRemove: UploadProps['onRemove'] = () => {
  file.value = undefined;
};

// 表单提交
const dataFormSubmitHandle = () => {
  if (!file.value) {
    ElMessage.error({
      message: '请选择需要导入的文件!',
    });
    return;
  }
  submitLoading.value = true;
  const formData = new FormData();
  formData.append('file', file.value);
  formData.append('overwrite', String(true));
  let headers = {} as any;
  if (app.tenantMode === "code") {
    headers.tenantCode = getCache(CacheTenantCode, { isParse: false }) || "";
  }
  axios({
    url: `${app.api}/data/personnel/student/upload-batch`,
    data: formData,
    method: 'post',
    headers: {
      ...headers,
      'Content-Type': 'multipart/form-data',
      authorization: `Bearer ${getToken()}`,
    }
  }).then(({ data }) => {
    submitLoading.value = false;
    if (data.failedCount > 0) {
      ElMessage.error({
        message: '上传失败',
      });
    } else {
      ElMessage.success({
        message: '上传成功',
      });
      visible.value = false;
      emit("refreshDataList");
    }
  });
};

defineExpose({
  init
});
</script>

<style lang="less" scoped>
.ax-upload {
  color: #000;

  &-tip {
    font-size: 16px;
    font-weight: bold;
    padding: 0 20px;
  }

  &-template {
    padding: 10px 20px;
    color: #999999;
    display: flex;
    align-items: center;

    .icon-svg {
      color: green;
    }

    a {
      text-decoration: underline;
    }
  }

  &-warp {
    width: 100%;
    padding: 0;
    text-align: center;
    line-height: 16px;
    background-color: #f8f8f8;
    padding: 20px;
    border-radius: 10px;
    border: 1px dashed #cccccc;

    &__tip {
      font-size: 11px;
      color: #666;
    }

    &__txt {
      font-size: 13px;
      color: #666;
      padding: 10px 0;
    }
  }
}
</style>